<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter='20'>
        <el-col :span='9'>
          <el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select" clearable
            @clear='getUserList'>
            <el-button slot="append" icon="el-icon-search" @click='serach'></el-button>
          </el-input>
        </el-col>
        <el-col :span='4'>
          <el-button type='primary' @click='isShowDialog'>添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type='index'></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope='scope'>
            <el-switch v-model="scope.row.mg_state" @change='userStatusChanged(scope.row)'>
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope='scope'>
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size='mini' @click='showeditDialog(scope.row.id)'></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size='mini' @click='delUser(scope.row.id)'></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size='mini' @click='setRole(scope.row)'></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <div class="block">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum" :page-sizes="[2, 3, 5, 10]" :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper" :total="queryInfo.total">
        </el-pagination>
      </div>
    </el-card>
    <!-- 添加用户对话框模态框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogvisiable" width="50%" @close='adddialogClose'>
      <!-- 内容主体区域 -->
      <el-form ref='addFormRef' :model="addForm" :rules="addFormRules" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogvisiable = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog title="修改用户"  :visible.sync="editDialogvisiable"  width="50%" @close="resetEditDialog">
      <el-form ref='editFormRef' :model="editForm" :rules="editFormRules" label-width="70px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogvisiable = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色"  :visible.sync="setRoleDialogVisiable"  width="50%">
      <el-form :model="userInfo" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名" prop="role_name">
            <el-select v-model="roleRightId" placeholder='请选择' @change='changeRoler(userInfo.id)'>
                <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value='item.id'>
                </el-option>
            </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisiable = false">取 消</el-button>
        <el-button type="primary" @click="changeRole()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 验证邮箱的规则
    var checkemail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (regEmail.test(value)) {
        // 验证合法
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    var checkmobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 验证合法
        return cb()
      }
      cb(new Error('请输入合法的手机号码'))
    }
    return {
    // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogvisiable: false,
      // 分配角色对话框的显示与隐藏
      setRoleDialogVisiable: false,
      // 添加用户得表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单的验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名字', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度为3到10之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 12, message: '用户名长度为6到12之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱账号', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      // 修改用户信息对话框的显示隐藏
      editDialogvisiable: false,
      // 查询到的用户信息对象
      editForm: {},
      // 修改信息表单的验证对象
      editFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户手机号', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      // 角色信息
      userInfo: {},
      // 获取的角色列表
      roleList: [],
      // 改变的分配的权限的id
      roleRightId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.userlist = res.data.users
      this.total = res.data.total
    },
    // 搜索功能
    serach () {
      this.queryInfo.pagenum = 1
      this.getUserList()
    },
    handleSizeChange (newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值得改变事件
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听switch状态开关的改变
    async userStatusChanged (userinfo) {
      console.log(userinfo)
      const {
        data: res
      } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      console.log(res)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 控制添加用户对话框得显示与隐藏
    isShowDialog () {
      this.addDialogvisiable = !this.addDialogvisiable
    },
    // 添加用户
    addUser () {
      // 预校验
      this.$refs.addFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.addDialogvisiable = false
        this.getUserList()
      })
    },
    // 监听添加用户对话框关闭事件
    adddialogClose () {
      console.log('123')
      console.log(this)
      this.$refs.addFormRef.resetFields()
    },
    // 展示编辑用户的对话框
    async showeditDialog (id) {
      const { data: res } = await this.$http.get('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取信息失败')
      this.editForm = res.data
      this.editDialogvisiable = !this.editDialogvisiable
    },
    // 监听用户修改信息表单的关闭重置事件
    resetEditDialog () {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息
    editUserInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('信息验证失败')
        const { data: res } = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
        if (res.meta.status !== 200) return this.$message.error('修改信息失败')
        this.$message.success('修改信息成功')
        this.editDialogvisiable = !this.editDialogvisiable
        this.getUserList()
      })
    },
    // 删除用户信息
    async delUser (id) {
      const resConfirm = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(resConfirm)
      if (resConfirm === 'confirm') {
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
      } else {
        this.$message.info('取消删除操作')
      }
      this.getUserList()
    },
    // 分配角色
    async setRole (userInfo) {
      this.userInfo = userInfo
      // 展示角色框之前获取所有的角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.roleList = res.data
      this.setRoleDialogVisiable = !this.setRoleDialogVisiable
    },
    // 改变权限
    async changeRole () {
      console.log(this.roleRightId)
      if (!this.roleRightId) {
        return this.$message.warning('您没有选择分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.roleRightId
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('分配角色失败')
      this.$message.success('分配角色成功')
      this.setRoleDialogVisiable = !this.setRoleDialogVisiable
      this.getUserList()
    },
    changeRoler (id) {
      console.log(this.roleRightId)
    }
  }
}

</script>

<style lang="less" scoped>
</style>
